/**
 * Created by yangfan on 2016/12/17.
 */
define(["app",'config/accessConfig'],function(app,accessConfig){
    app.service("auth", ["$http","$rootScope","$q","$state","$location", function($http,$rootScope,$q,$state){
        var defer = $q.defer();
        var url ="http://"+allUrl+":8080/",base = "elink_user/api/user/getBaseUeserInfo",userBase = "elink_user/api/user/logOut";
        var formState = "";
        var fromParams = "";
        //http://"+allUrl+":8080/elink_user/api/user/getBaseUeserInfo

        if(typeof localStorage.seed =="undefined" ||localStorage.authToken=="undefined"){
            localStorage.seed = "";
            localStorage.authToken = "";
        }
        var getFormState = function (){
           return formState
        };
        var getFromParams = function(){
            return fromParams;
        }
       var getUserInfo = function (){
           $http({
               method:"GET",
               url:url +  base +"?seed="+ localStorage.seed + "&authToken=" + localStorage.authToken,
               //withCredentials:true
           }).success(function(response){
               if(response.msg == "success"){
                   $rootScope.userLoginInfo.data = response.data;
                   $rootScope.userLoginInfo.logged = true;
               }
           }).error(function(){
               var defer = $q.defer();
               $rootScope.userLoginInfo.data = "";
               $rootScope.userLoginInfo.logged = false;
           });
           defer.resolve();
           return defer.promise;
        };
        $rootScope.userLoginInfo = {
            data:{},
            logged:false
        };
        if(localStorage.hasOwnProperty("seed")&&localStorage.hasOwnProperty("authToken")){
            getUserInfo();
        }
        var urlPermissions = {};
        var removeCookie = function(){
            var defer = $q.defer();
            localStorage.removeItem("seed");
            localStorage.removeItem("authToken");
            $rootScope.userLoginInfo.data = "";
            $rootScope.userLoginInfo.logged = false;
            defer.resolve();
            return defer.promise;
        };

        var loginOut =function (){
         return  $http({
              method:"POST",
              url:url +  userBase +"?seed="+ localStorage.seed + "&authToken=" + localStorage.authToken,
          })
        };
        function _isArrayContain (Arr,value){
            return Arr.some(function(item){
                return item == value
            })
        }
        // 因为初始化时执行 获取登录信息 和 路由跳转 是异步关系 所以异步请求信息不能作为路由跳转时的条件
        function _isLogion(){
            if(!!localStorage.seed){
                return true
            }else {
                return false
            }
        }
        var isAccessUrl = function(state){
            getUserInfo()
            if((!_isLogion()&& _isArrayContain(accessConfig.user,state)) ||(!_isLogion()&& _isArrayContain(accessConfig.company,state))){
                alert('请先登录，在访问该页面');
                return false
            } else if($rootScope.userLoginInfo.data.userType == 1 && _isArrayContain(accessConfig.company,state)){
                $state.go('indexCtrl');
                return false
            }else if($rootScope.userLoginInfo.data.userType == 2 && _isArrayContain(accessConfig.user,state)){
                $state.go('indexCtrl');
                return false
            }else {
                return true
            }
        };


        return {
            //重新登录
            reLogin:function(){
                return getUserInfo()

            },
            loginOut:function(){
                return  loginOut()
            },
            removeCookie:function(){
                return removeCookie()
            },
            getFormState:function(){
                return getFormState();
            },
            getFromParams:function(){
                return getFromParams();
            },
            setFormState:function(newState){
                formState = newState ;
            },
            setFromParams:function(newParams){
                fromParams = newParams;
            },
            isLogin:function(){
                var defer = $q.defer();
                if(!$rootScope.userLoginInfo.logged){
                    $rootScope.jumpTo();
                    return ;
                }
                defer.resolve();
                return defer.promise;
            },
            isUser:function(){
                var defer = $q.defer();
                if(!$rootScope.userLoginInfo.logged){
                   alert('请先登录，再执行操作')
                    return ;
                }
                else if($rootScope.userLoginInfo.data.userType == 2){
                    alert('当前为企业用户，不支持该项操作')
                    return ;
                }
                defer.resolve();
                return defer.promise;
            },
            isPersonLogin:function(){
                var defer = $q.defer();
                if($rootScope.userLoginInfo.data.userType != 1){
                    $state.go('indexCtrl');
                    return ;
                }
                defer.resolve();
                return defer.promise;
            },
            isCompanyLogin:function(){
                var defer = $q.defer();
                if($rootScope.userLoginInfo.data.userType != 2){
                    $state.go('indexCtrl');
                    return ;
                }
                defer.resolve();
                return defer.promise;
            },
            isAccessUrl:function(state){
                return isAccessUrl(state);
            }
        }
    }]);
    app.run(["$rootScope",'$state', "auth", function($rootScope, $state, auth){
        // 点击未登录 跳转到登录页面 方法挂在rootScope 上
        $rootScope.jumpTo = function(){
          $state.go('login',{type:'logion'});
        };
        $rootScope.jumpToHelp = function(state){
            $state.go(state);
        };
        //全局搜索关键词
        $rootScope.GLOBALKEYWORD = "";
        //每次刷新页面清除sessionStorage 全局搜索项
        sessionStorage.removeItem("searchKeyWord");

        //设置登录登出监听
        $rootScope.$on("logOutEvent",function(){
            auth.loginOut().success(function(data){
                localStorage.removeItem("seed");
                localStorage.removeItem("authToken");
                //清空缓存
                    auth.removeCookie().then(function(){
                        auth.reLogin().then(function(){
                            auth.setFormState("");
                            $state.go("indexCtrl");
                        })
                    })
            }).error(function(){
            })
        });
        $rootScope.$on("loginEventSuccess",function(a,b){
            localStorage.seed = b.seed;
            localStorage.authToken  = b.authToken ;
            auth.reLogin().then(function(){
                var state = auth.getFormState();
                var params = auth.getFromParams();
                if(state == "enterpriselogin"){
                    state = "indexCtrl"
                }
                if(state == "logion"){
                    state = "indexCtrl"
                }
                if(state == 'eng.loginedReseted'){
                    state = "indexCtrl"
                }
                if(state == "myaccount"){
                	state == "indexCtrl"
                }
                if(b.type == "company"){
                    $state.go("comIndexCtrl");
                }else{
                    if(!state){
                        $state.go("indexCtrl");
                    }else{
                        $state.go(state,params);
                        console.log(state,params)
                    }
                }

            });
        });

        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            $rootScope.routerToStateName = toState.name;
            if(toState.name =="login"){
                auth.setFormState(fromState.name);
                auth.setFromParams(fromParams);
            }
            if(fromState.name.indexOf("search")>-1&&toState.name.indexOf("search")<0){
                $rootScope.GLOBALKEYWORD = ""
            }
            //鉴别当前角色是否具有路由访问权限
            if( !auth.isAccessUrl(toState.name)){
                $state.go("indexCtrl");
                event.preventDefault();
            }

            // 路由访问控制
            //if(toState.name!="page.login" && !auth.isAccessUrl(toState.name)) {
            //    // 查看是否需要登录：
            //    var user = $sessionStorage.USER;
            //    if(user == null) {
            //        event.preventDefault();
            //        $state.go("page.login");
            //        return;
            //    }
            //    event.preventDefault();
            //    $state.go("page.error");
            //}
        });
        $rootScope.$on("$stateChangeSuccess", function (event, currentRoute, previousRoute) {
            window.scrollTo(0, 0);
        });
    }])

});
